"use strict";
const Service = require("egg").Service;
const { httpCode } = require("../../utils/userConfig");
const AuthException = require('../../exception/authException');
const SystemErrException = require("../../exception/systemError");
const Qiniu = require("../../utils/qiniu")

class StaffMgmtService extends Service {

  // 添加员工
  async add(user) {
    try {
      const { ctx } = this;
      delete user.id;
      delete user.avatar;
      await ctx.model.Organization.Staff.create(user);
      return {
        code: httpCode.SUCCESS,
        message: "员工添加成功"
      }
    } catch (error) {
      throw new SystemErrException("员工添加异常：" + error);
    }
  }

  // 员工列表
  async list(requestData) {
    try {
      const { ctx, app } = this;
      let { currentPage = 1, pageSize = 999, userName } = requestData;
      if (userName) {
        searchCondition = {
          userName: {
            [Op.substring]: 'userName',
          }
        }
      }
      let staff = await ctx.model.Organization.Staff.findAll({
        include: [{
          model: ctx.model.Organization.Role
        }, {
          model: ctx.model.Organization.Departments,
          include: {
            model: ctx.model.Organization.Units
          }
        }],
        order: [['create_date', 'desc']],
        offset: (Number(currentPage) - 1) * Number(pageSize),
        limit: Number(pageSize),
      });
      staff = JSON.parse(JSON.stringify(staff));
      staff.forEach(item => {
        let Department = item.ODepartment;
        let Unit = Department.OUnit;
        let departmentUnit = '';
        if (Department.name && Unit.name) {
          departmentUnit = `${Unit.name}-${Department.name}`
        }
        let roles = [];
        if (item.ORoles.length != 0) {
          roles = item.ORoles.map(role => role.name);
        }
        item.roles = roles.join(",");
        item.departmentUnit = departmentUnit;
      });

      let count = await ctx.model.Organization.Staff.count();

      return {
        data: {
          data: staff,
          count
        },
        code: httpCode.SUCCESS,
        message: '员工列表查询成功！'
      }
    } catch (error) {
      throw new SystemErrException("员工列表查询异常：" + error);
    }
  }

  // 删除员工
  async delete({ id }) {
    try {
      const { ctx } = this;
      await ctx.model.Organization.Staff.destroy({
        where: { id }
      });
      return {
        code: httpCode.SUCCESS,
        message: "员工信息删除成功！"
      }
    } catch (error) {
      throw new SystemErrException("员工信息删除异常：" + error);
    }
  }

  async update(staff) {
    try {
      let { id } = staff;
      await this.ctx.model.Organization.Staff.update(
        staff,
        {
          where: { id },
        }
      );
      return {
        code: httpCode.SUCCESS,
        message: "员工信息更新成功！",
      };
    } catch (error) {
      throw new SystemErrException("员工信息更新异常：" + error);
    }
  }

  async updateStaffAuthority(postData) {
    let transaction;
    try {
      const { ctx } = this;
      transaction = await this.ctx.model.transaction();
      // 创建关联关系 
      const staffRoles = postData.selectAuthorityIds.map(item => {
        return {
          staffId: postData.staffId,
          roleId: item
        }
      })
      // 删除之前的用户权限
      await ctx.model.Organization.StaffRole.destroy({
        where: { staffId: postData.staffId }
      })
      await ctx.model.Organization.StaffRole.bulkCreate(staffRoles);
      return {
        code: httpCode.SUCCESS,
        message: "权限编辑成功"
      }
    } catch (error) {
      this.ctx.logger.error(error);
      await transaction.rollback();
    }
  }
}

module.exports = StaffMgmtService;
